package com.example.hcd.functionactivity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.hcd.R;
import com.example.hcd.internet.InternetKeep;
import com.example.hcd.internet.URLS;
import com.example.hcd.tool.MyLoadingDialog;
import com.example.hcd.tool.ToastHelp;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

public class UpdateManager
{
	/* 下载中 */
	private static final int DOWNLOAD = 1;
	/* 下载结束 */
	private static final int DOWNLOAD_FINISH = 2;
	/* 保存解析的XML信息 */
	// HashMap<String, String> mHashMap;
	/* 下载保存路径 */
	private String mSavePath;
	/* 记录进度条数量 */
	private int progress;
	/* 是否取消更新 */
	private boolean cancelUpdate = false;

	private Context mContext;
	/* 更新进度条 */
	private ProgressBar mProgress;
	private Dialog mDownloadDialog;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg)
		{
			switch (msg.what) {
			// 正在下载
			case DOWNLOAD:
				// 设置进度条位置
				mProgress.setProgress(progress);
				break;
			case DOWNLOAD_FINISH:
				// 安装文件
				installApk();
				break;
			default:
				break;
			}
		};
	};

	public UpdateManager(Context context) {
		this.mContext = context;
	}

	public void findUpdata()
	{

		int versionCode = getVersionCode(mContext);
		// 版本判断
		if (InternetKeep.getInstence().getVersionCode() > versionCode)
		{
			showNoticeDialog();
		}
	}

	public void findUpDataByToast()
	{
		int versionCode = getVersionCode(mContext);
		// 版本判断
		if (InternetKeep.getInstence().getVersionCode() > versionCode)
		{
			showNoticeDialog();
		} else
		{
			Toast.makeText(mContext, "版本已达最新", Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 检测软件更新
	 */
//	public void checkUpdate()
//	{
//		new LoadVersionInfo().execute();
//
//	}

	private class LoadVersionInfo extends AsyncTask<String, Integer, String>
	{

		HttpClient getClient = null;
		HttpResponse response = null;
		BufferedReader reader = null;
		MyLoadingDialog myDialog;

		@Override
		protected void onPreExecute()
		{
			myDialog = new MyLoadingDialog(mContext, getClient, "检测版本中..", false);

		}

		@Override
		protected String doInBackground(String... params)
		{
			String result = null;
			try
			{
				// 得到HttpClient对象
				getClient = new DefaultHttpClient();
				// 得到HttpGet对象
				HttpGet request = new HttpGet(URLS.getVersion());
				response = getClient.execute(request);

				if (response != null)
				{
					StatusLine line = response.getStatusLine();
					if (line.getStatusCode() == 200)
					{
						reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
						StringBuilder sb = new StringBuilder();
						for (String s = reader.readLine(); s != null; s = reader.readLine())
						{
							sb.append(s);
						}
						result = sb.toString();

					}
				}
			} catch (Exception e)
			{

			} finally
			{
				if (reader != null)
				{
					try
					{
						reader.close();
					} catch (IOException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result)
		{
			// myDialog.dimiss();
			if (!TextUtils.isEmpty(result))
			{

				if (result.contains("error"))
				{

					JSONObject jsonObject;
					try
					{
						jsonObject = new JSONObject(result);
						String msg = jsonObject.getString("msg");
						ToastHelp.doToastInTop(mContext, msg);
					} catch (JSONException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				} else
				{

					try
					{
						JSONObject jsonObject = new JSONObject(result);
						String msg = jsonObject.getString("versionCode");
						int serviceCode = Integer.valueOf(msg);

						// 获取当前软件版本
						int versionCode = getVersionCode(mContext);
						// 版本判断
						if (serviceCode > versionCode)
						{
							showNoticeDialog();
						} else
						{
							Toast.makeText(mContext, "版本已达最新", Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					myDialog.dimiss();
				}

			} else
			{
				ToastHelp.doToastInTop(mContext, "获取系统信息失败");
				myDialog.dimiss();
			}
		}

	}

	/**
	 * 检查软件是否有更新版本
	 * 
	 * @return
	 */
	// private boolean isUpdate()
	// {
	//// 获取当前软件版本
	// int versionCode = getVersionCode(mContext);
	// 把version.xml放到网络上，然后获取文件信息
	// InputStream inStream =
	//// ParseXmlService.class.getClassLoader().getResourceAsStream("version.xml");
	// 解析XML文件。 由于XML文件比较小，因此使用DOM方式进行解析
	// ParseXmlService service = new ParseXmlService();
	// try
	// {
	// mHashMap = service.parseXml(inStream);
	// } catch (Exception e)
	// {
	// e.printStackTrace();
	// }
	// if (null != mHashMap)
	// {
	// int serviceCode = Integer.valueOf(mHashMap.get("version"));
	// // 版本判断
	// if (serviceCode > versionCode)
	// {
	// return true;
	// }
	// }
	// return false;
	// }

	/**
	 * 获取软件版本号
	 * 
	 * @param context
	 * @return
	 */
	private int getVersionCode(Context context)
	{
		int versionCode = 0;
		try
		{
			// 获取软件版本号，对应AndroidManifest.xml下android:versionCode
			versionCode = context.getPackageManager().getPackageInfo("com.example.hcd", 0).versionCode;
		} catch (NameNotFoundException e)
		{
			e.printStackTrace();
		}
		return versionCode;
	}

	/**
	 * 显示软件更新对话框
	 */
	private void showNoticeDialog()
	{
		// 构造对话框
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle(R.string.soft_update_title);
		builder.setMessage(R.string.soft_update_info);
		// 更新
		builder.setPositiveButton(R.string.soft_update_updatebtn, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
				// 显示下载对话框
				showDownloadDialog();
			}
		});
		// 稍后更新
		builder.setNegativeButton(R.string.soft_update_later, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		});
		Dialog noticeDialog = builder.create();
		noticeDialog.show();
	}

	/**
	 * 显示软件下载对话框
	 */
	private void showDownloadDialog()
	{
		// 构造软件下载对话框
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle(R.string.soft_updating);
		// 给下载对话框增加进度条
		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.softupdate_progress, null);
		mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
		builder.setView(v);
		// 取消更新
		builder.setNegativeButton(R.string.cancel, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
				// 设置取消状态
				cancelUpdate = true;
			}
		});
		mDownloadDialog = builder.create();
		mDownloadDialog.show();
		// 下载文件
		downloadApk();
	}

	/**
	 * 下载apk文件
	 */
	private void downloadApk()
	{
		// 启动新线程下载软件
		new downloadApkThread().start();

		// // 判断SD卡是否存在，并且是否具有读写权限
		// if
		// (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
		// {
		// new DownloadInfo().execute();
		// }
	}

	/**
	 * 下载文件线程
	 * 
	 * @author coolszy
	 * @date 2012-4-26
	 * @blog http://blog.92coding.com
	 */

	private class DownloadInfo extends AsyncTask<String, Integer, String>
	{
		private String errorId = "-1";

		@Override
		protected void onPreExecute()
		{
		}

		@Override
		protected String doInBackground(String... params)
		{
			String result = null;
			try
			{
				// 获得存储卡的路径
				String sdpath = Environment.getExternalStorageDirectory() + "/venadaOA/";
				URL url = new URL(URLS.getApkDown());
				// 创建连接
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.connect();
				// 获取文件大小
				int length = conn.getContentLength();
				// 创建输入流
				InputStream is = conn.getInputStream();

				File file = new File(sdpath);
				// 判断文件目录是否存在
				if (!file.exists())
				{
					file.mkdir();
				}
				File apkFile = new File(sdpath, "hcdOA.apk");
				FileOutputStream fos = new FileOutputStream(apkFile);
				int count = 0;
				// 缓存
				byte buf[] = new byte[1024];
				// 写入到文件中
				do
				{
					int numread = is.read(buf);
					count += numread;
					// 计算进度条位置
					progress = (int) (((float) count / length) * 100);
					// 更新进度
					mHandler.sendEmptyMessage(DOWNLOAD);
					if (numread <= 0)
					{
						// 下载完成
						mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
						break;
					}
					// 写入文件
					fos.write(buf, 0, numread);
				} while (!cancelUpdate);// 点击取消就停止下载.
				fos.close();
				is.close();
			} catch (Exception e)
			{
				// mDownloadDialog.dismiss();
			} finally
			{
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result)
		{
		}

	}

	private class downloadApkThread extends Thread
	{
		@Override
		public void run()
		{
			try
			{
				// 判断SD卡是否存在，并且是否具有读写权限
				if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
				{
					// 获得存储卡的路径
					mSavePath = Environment.getExternalStorageDirectory() + "/venadaOA/";
					// mSavePath = sdpath + "download";
					URL url = new URL(URLS.getApkDown());
					// 创建连接
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();
					conn.connect();
					// 获取文件大小
					int length = conn.getContentLength();
					// 创建输入流
					InputStream is = conn.getInputStream();

					File file = new File(mSavePath);
					// 判断文件目录是否存在
					if (!file.exists())
					{
						file.mkdir();
					}
					File apkFile = new File(mSavePath, "hcdOA.apk");
					FileOutputStream fos = new FileOutputStream(apkFile);
					int count = 0;
					// 缓存
					byte buf[] = new byte[1024];
					// 写入到文件中
					do
					{
						int numread = is.read(buf);
						count += numread;
						// 计算进度条位置
						progress = (int) (((float) count / length) * 100);
						// 更新进度
						mHandler.sendEmptyMessage(DOWNLOAD);
						if (numread <= 0)
						{
							// 下载完成
							mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
							break;
						}
						// 写入文件
						fos.write(buf, 0, numread);
					} while (!cancelUpdate);// 点击取消就停止下载.
					fos.close();
					is.close();
				}
			} catch (MalformedURLException e)
			{
				e.printStackTrace();
			} catch (IOException e)
			{
				e.printStackTrace();
			}
			// 取消下载对话框显示
			mDownloadDialog.dismiss();
		}
	};

	/**
	 * 安装APK文件
	 */
	private void installApk()
	{
		File apkfile = new File(mSavePath, "hcdOA.apk");
		if (!apkfile.exists())
		{
			return;
		}
		// 通过Intent安装APK文件
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
		mContext.startActivity(i);
	}
}
